var express = require("express");
var router = express.Router();
const multer = require("multer");
const fs = require("fs");
const { Friend } = require("../model/model");

const upload = multer({
  dest: "uploads/",
});

router.post("/upload", upload.single("file"), (req, res) => {
  // 获取文件信息
  const file = req.file;
  // 获取切片文件名称
  let filename = req.body.filename;
  filename = filename.slice(0, filename.length - 4);
  // 获取切片文件索引值
  const index = req.body.index;
  // 配置切片文件的路径 uploads/文件名
  const chunkDir = `uploads/${filename}`;
  console.log(file);
  // 判断切片文件路径是否存在，不存在进行创建文件夹
  if (!fs.existsSync(chunkDir)) {
    fs.mkdirSync(chunkDir);
  }
  // 配置切片文件路径文件夹下的索引文件   uploads/文件名/0
  const chunkPath = `${chunkDir}` + "/" + `${index}`;
  // 将切片文件的名称 移动到 现在文件路径
  fs.renameSync(file.path, chunkPath);
  res.send("Chunk uploaded successfully");
});

router.post("/merge", (req, res) => {
  // 获取文件名称
  let { filename } = req.body;
  console.log(filename);
  const fileType = filename.slice(filename.lastIndexOf(".") + 1);
  filename = filename.slice(0, filename.length - 4);
  // 视频文件夹路径
  const chunkDir = `uploads/${filename}`;
  // 视频合成完的路径
  const filePath = `uploads/${filename}.` + fileType;

  // 读取文件夹中的所有索引的切片文件 并排序
  const chunks = fs.readdirSync(chunkDir);
  chunks.sort((a, b) => a - b);

  // 遍历切片文件
  chunks.forEach((chunk, index) => {
    // 获取切片文件夹下的切片文件路径
    const chunkPath = `${chunkDir}/${chunk}`;
    // 将切片文件追加到 新文件 末尾
    fs.appendFileSync(filePath, fs.readFileSync(chunkPath));
    // 删除切片文件路径
    fs.unlinkSync(chunkPath);
  });
  // 删除文件夹
  fs.rmdirSync(chunkDir);
  res.send({
    filePath: 'http://localhost:3000/' + filePath,
    code: 200,
    message: "文件合并完成"
  });
});









































router.get('/getData', async (req, res) => {
  let data = await Friend.find()
  res.send({
    data,
    code: 200,
    msg: "获取成功"
  })
})


router.post('/add', async (req, res) => {
  let infos = await Friend.findOne({ _id: req.body.fid })
  console.log(infos);
  console.log(req.body);

  await Friend.create({
    files: req.body.files,
    content: req.body.content,
    name: infos.name,
    uid: infos.uid,
    date: new Date(),
    lovenum: 0,
    logs: [],
    photo: infos.photo
  })
  res.send({
    code: 200,
    msg: "添加成功"
  })
})




module.exports = router;
